import { Provide, Inject } from '@midwayjs/core';
import { BaseService } from '@cool-midway/core';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository } from 'typeorm'; 
import { AutomationConditionEntity } from '../../entity/condition';
import { AutomationTaskEntity } from '../../entity/task';
import { AutomationPipelineEntity } from '../../entity/pipeline';
import { AutomationEngineService } from './engine';

/**
 * 自动化流水线
 */
@Provide()
export class AutomationPipelineService extends BaseService {
  @InjectEntityModel(AutomationPipelineEntity)
  automationPipelineEntity: Repository<AutomationPipelineEntity>;

  @InjectEntityModel(AutomationConditionEntity)
  automationConditionEntity: Repository<AutomationConditionEntity>;

  @InjectEntityModel(AutomationTaskEntity)
  automationTaskEntity: Repository<AutomationTaskEntity>;

  @Inject()
  automationEngineService: AutomationEngineService;

  /**
   * 新增流水线
   * @param params
   */
  async addPipeline(params: any) {
    const { conditions, tasks, ...pipeline } = params;
    const pipelineResult = await this.automationPipelineEntity.save(pipeline);

    if (conditions && conditions.length > 0) {
      conditions.forEach(condition => condition.pipelineId = pipelineResult.id);
      /* 触发条件 */
      await this.automationConditionEntity.save(conditions);
    }

    if (tasks && tasks.length > 0) {
      tasks.forEach(task => task.pipelineId = pipelineResult.id);
      /* 执行 */
      await this.automationTaskEntity.save(tasks);
    }

    // 如果流水线启用，启动监控
    if (pipeline.status === 1) {
      await this.automationEngineService.startPipelineMonitoring(pipelineResult.id);
    }

    return pipelineResult;
  }

  /**
   * 更新流水线
   * @param params
   */
  async updatePipeline(params: any) {
    const { conditions, tasks, id, ...pipeline } = params;

    await this.automationPipelineEntity.update(id, pipeline);

    if (conditions) {
      await this.automationConditionEntity.delete({ pipelineId: id });
      if (conditions.length > 0) {
        conditions.forEach(condition => condition.pipelineId = id);
        await this.automationConditionEntity.save(conditions);
      }
    }

    if (tasks) {
      await this.automationTaskEntity.delete({ pipelineId: id });
      if (tasks.length > 0) {
        tasks.forEach(task => task.pipelineId = id);
        await this.automationTaskEntity.save(tasks);
      }
    }

    // 重新加载流水线监控
    await this.automationEngineService.reloadPipeline(id);

    return '更新成功';
  }

  /**
   * 删除流水线
   * @param ids
   */
  async deletePipeline(ids: number[]) {
    // 停止监控
    for (const id of ids) {
      await this.automationEngineService.stopPipelineMonitoring(id);
    }
    
    await this.automationPipelineEntity.delete(ids);
    await this.automationConditionEntity.delete({ pipelineId: ids as any });
    await this.automationTaskEntity.delete({ pipelineId: ids as any });
    return '删除成功';
  }

  /**
   * 获取流水线详情
   * @param id
   */
  async pipelineDetail(id: number) {
    const pipeline = await this.automationPipelineEntity.findOneBy({ id });
    if (!pipeline) {
      return null;
    }
    const conditions = await this.automationConditionEntity.findBy({ pipelineId: id });
    const tasks = await this.automationTaskEntity.findBy({ pipelineId: id });
    return { ...pipeline, conditions, tasks };
  }

  /**
   * 启用/禁用流水线
   * @param id
   * @param status
   */
  async togglePipelineStatus(id: number, status: number) {
    await this.automationPipelineEntity.update(id, { status });
    
    if (status === 1) {
      // 启用：开始监控
      await this.automationEngineService.startPipelineMonitoring(id);
    } else {
      // 禁用：停止监控
      await this.automationEngineService.stopPipelineMonitoring(id);
    }
    
    return '操作成功';
  }

  /**
   * 手动触发流水线
   * @param id
   */
  async triggerPipeline(id: number) {
    await this.automationEngineService.triggerPipeline(id);
    return '触发成功';
  }

  /**
   * 获取条件类型选项
   */
  async getConditionTypes() {
    return [
      { value: 0, label: '气象条件' },
      { value: 1, label: '设备条件' },
      { value: 2, label: '定时条件' }
    ];
  }

  /**
   * 获取气象条件类型选项
   */
  async getWeatherTypes() {
    return [
      { value: 0, label: '温度' },
      { value: 1, label: '湿度' },
      { value: 2, label: '天气' },
      { value: 3, label: 'PM2.5' },
      { value: 4, label: '空气质量' },
      { value: 5, label: '日落日出' },
      { value: 6, label: '风速' }
    ];
  }

  /**
   * 获取比较方式选项
   */
  async getCompareTypes() {
    return [
      { value: 0, label: '大于' },
      { value: 1, label: '小于' },
      { value: 2, label: '等于' },
      { value: 3, label: '不等于' },
      { value: 4, label: '大于等于' },
      { value: 5, label: '小于等于' }
    ];
  }

  /**
   * 获取任务操作类型选项
   */
  async getActionTypes() {
    return [
      { value: 0, label: '开' },
      { value: 1, label: '关' },
      { value: 2, label: '完全同步' }
    ];
  }
}